//
//  BluetoothManager.m
//  Anyair
//
//  Created by karlcool on 14-5-18.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "BluetoothManager.h"

@implementation BluetoothManager
@synthesize resultArray;

+(BluetoothManager*)createManager {
    
    if (blManager==nil) {
        blManager = [[BluetoothManager alloc]init];
        blManager.senor = [[SerialGATT alloc]init];
        [blManager.senor setup];
        blManager.headArray = @[@"255",@"255",@"255",@"255",@"255"];
    }
    blManager.resultArray = [[NSMutableArray alloc]init];
    return blManager;
}

#pragma mark - 连接之前连接的设备
- (void)connectDevice {
    
    blManager.senor.delegate = self;
    int result = [blManager.senor findHMSoftPeripherals:5];
    if (result==-1) {
        [self performSelector:@selector(findAgain) withObject:nil afterDelay:0.5];
    }
}

- (void)findAgain {
    [blManager.senor findHMSoftPeripherals:5];
}

#pragma mark - 从硬件获取PM数值
- (void)getPMData {
    currentType = 0;
    PMFlag2 = YES;
    [blManager.senor setDelegate:self];
    NSData *data = [@"$TK&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];

}

#pragma mark - 从硬件获取CO2数值
- (void)getCO2Data {
    currentType = 1;
    [blManager.senor setDelegate:self];
    NSData *data = [@"$CV&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];
    NSLog(@"co2测试中");
}

#pragma mark - 从硬件获取CO2数值,实时检测
- (void)getKeepCO2Data {
    co2Timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(getCO2Data) userInfo:nil repeats:YES];
    
}

- (void)closeKeepCO2 {
    [co2Timer invalidate];
    co2Timer = nil;
}

#pragma mark - 从硬件获取甲醛数值
- (void)getMethanalData {
    currentType = 2;
    [blManager.senor setDelegate:self];
    NSData *data = [@"$CV&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];
}

#pragma mark - 从硬件获取温度数值
- (void)getTemperatureData {
    currentType = 3;
    [blManager.senor setDelegate:self];
    NSData *data = [@"$CV&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];
}

#pragma mark - 从硬件获取湿度数值
- (void)getHumidityData {
    currentType = 4;
    [blManager.senor setDelegate:self];
    NSData *data = [@"$CV&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];
}

#pragma mark - 从硬件获取电量
- (void)getBatteryData {
    currentType = 5;
    [blManager.senor setDelegate:self];
    NSData *data = [@"$CV&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];

}

#pragma mark - 设备回调
#pragma mark - 硬件返回值

-(void) peripheralFound:(CBPeripheral *)peripheral {
    
    NSString *connectedUUID = [[NSUserDefaults standardUserDefaults]objectForKey:@"connectedUUID"];//从用户配置中取出最后连接的设备UUID
    NSLog(@"发现的设备UUID:%@",peripheral.identifier.UUIDString);
    
    if ([connectedUUID isEqualToString:peripheral.identifier.UUIDString]) {
        
        [blManager.senor connect:peripheral];
        self.isConnected = YES;
    }
}


-(void) serialGATTCharValueUpdated:(NSString *)UUID value:(NSData *)data {
    
    NSLog(@"返回值%@",data);
    
    Byte *bt = (Byte *)[data bytes];
    NSMutableArray *tempArray = [[NSMutableArray alloc]init];
    
    for(int i=0;i<data.length;i++) {
        [tempArray addObject:[NSString stringWithFormat:@"%i",bt[i]]];
    }
    //切除前面的5个255,直接保留数据部分
    if (tempArray.count>5) {
        [resultArray removeAllObjects];
        [resultArray addObjectsFromArray:self.headArray];
        [resultArray addObjectsFromArray:tempArray];
        NSLog(@"结果%@",resultArray);
        
    }
    
    if (!flag&&currentType!=0&&currentType!=-1) {
        [self performSelector:@selector(decodeValue) withObject:nil afterDelay:1.5];
        flag = YES;
    }
    if (!flag&&currentType==0&&PMFlag2) {
        
        PMTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(senderPMOrder) userInfo:nil repeats:YES];
        flag = YES;
        
    }
    //检测PM的特殊处理
    if (currentType==-1) {
        
        if (!PMFlag1) {
            [self performSelector:@selector(getPMValue) withObject:nil afterDelay:39];
            PMFlag1 = YES;
        }
    }
    
}


- (void)getPMValue {
    [PMTimer invalidate];
    PMTimer = nil;
    currentType = 0;
    if (resultArray.count>5) {
        [self decodeValue];
    }
}

#pragma mark - 发送连续检测PM命令
- (void)senderPMOrder {
    currentType = -1;
    NSData *data = [@"$TG&" dataUsingEncoding:NSASCIIStringEncoding];
    [blManager.senor write:blManager.senor.activePeripheral data:data];
}


#pragma mark - 解析数据
- (void)decodeValue {
    NSString *result;
    switch (currentType) {
        case 0:
            if (resultArray.count>=23) {
                int T1 = ((NSString*)resultArray[8]).intValue;
                int T2 = ((NSString*)resultArray[9]).intValue;
                int T3 = ((NSString*)resultArray[10]).intValue;
                int T4 = ((NSString*)resultArray[11]).intValue;
                int PM25 = (T1<<24)|(T2<<16)|(T3<<8)|T4;
                int T5 = ((NSString*)resultArray[12]).intValue;
                int T6 = ((NSString*)resultArray[13]).intValue;
                int T7 = ((NSString*)resultArray[14]).intValue;
                int T8 = ((NSString*)resultArray[15]).intValue;
                int PM50 = (T5<<24)|(T6<<16)|(T7<<8)|T8;
                int T9 = ((NSString*)resultArray[16]).intValue;
                int T10 = ((NSString*)resultArray[17]).intValue;
                int T11 = ((NSString*)resultArray[18]).intValue;
                int T12 = ((NSString*)resultArray[19]).intValue;
                int PM100 = (T9<<24)|(T10<<16)|(T11<<8)|T12;
                result = [NSString stringWithFormat:@"%i,%i,%i",PM25/100000 *15,PM50/100 *30,PM100/10*150];
                NSLog(@"PM%@",result);
            } else {
                result = @"false";
            }
            break;
            
        case 2:
            if (resultArray.count>=12) {
                int T1 = ((NSString*)resultArray[10]).intValue;
                int T2 = ((NSString*)resultArray[11]).intValue;
                float T = (float)((T1*256)|T2);
                result = [NSString stringWithFormat:@"%.2f",T/100];
                NSLog(@"甲醛%@",result);
            } else {
                result = @"false";
            }
            break;
            
        case 1:
            if (resultArray.count>=10) {
                int T1 = ((NSString*)resultArray[8]).intValue;
                int T2 = ((NSString*)resultArray[9]).intValue;
                result = [NSString stringWithFormat:@"%i",(T1*256)|T2];
                NSLog(@"二氧化碳%@",result);
            } else {
                result = @"false";
            }
            break;
            
        case 3:
            if (resultArray.count>=16) {
                int T1 = ((NSString*)resultArray[14]).intValue;
                int T2 = ((NSString*)resultArray[15]).intValue;
                int T = (T1*256)|T2;
                result = [NSString stringWithFormat:@"%i",T/10];
                NSLog(@"温度%@",result);
            } else {
                result = @"false";
            }
            break;
            
        case 4:
            if (resultArray.count>=14) {
                int T1 = ((NSString*)resultArray[12]).intValue;
                int T2 = ((NSString*)resultArray[13]).intValue;
                int T = (T1*256)|T2;
                result = [NSString stringWithFormat:@"%i",T/10];
                NSLog(@"湿度%@",result);
            }
            break;
            
        case 5:
            if (resultArray.count>=10) {
                float battery1 = ((NSString*)resultArray[8]).floatValue;
                float battery2 = ((NSString*)resultArray[9]).floatValue;
                result = [NSString stringWithFormat:@"%f",battery1 +battery2/100];
        
                NSLog(@"电量%@",result);
            } else {
                result = @"false";
            }
            break;
            
        default:
            break;
    }
    
    if ([self.delegate respondsToSelector:@selector(dataDidUpdate:WhichType:)]) {
        [self.delegate dataDidUpdate:result WhichType:currentType];
    }
    [resultArray removeAllObjects];
    flag = NO;
    PMFlag1 = NO;
    PMFlag2 = NO;
}

-(void)sensorReady {
    
}

- (void) setConnect {
    self.isConnected = YES;
    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:[UIApplication sharedApplication].keyWindow];
    [[UIApplication sharedApplication].keyWindow addSubview:shortHub];
    [shortHub setLabelText:[NSString stringWithFormat:@"已连接到%@",[BluetoothManager createManager].senor.activePeripheral.name]];
    [shortHub setMode:MBProgressHUDModeText];
    [shortHub hide:YES afterDelay:1.5];
    [shortHub show:YES];
}

- (void) setDisconnect {
    self.isConnected = NO;
    NSString *result = @"false";
    currentType = 100;
    if ([self.delegate respondsToSelector:@selector(dataDidUpdate:WhichType:)]) {
        [self.delegate dataDidUpdate:result WhichType:currentType];
    }
}
@end
